qui(function (require, exports, module) {
    Ticket.Util = $.extend(true, {}, EpgWeb.Util, {
        formatter: {
            ticket_status: function (v, o, r) {
                switch (v) {
                    case 999:
                        return "处理终止";
                    case 1:
                        return "处理完成";
                    case 0:
                        return "待处理";
                    default :
                        return "unknown " + v;
                }
            },
            operator_ticket_data: function (v, o, r) {
                var htmlArr = [];
                var isOwner = Ticket.Util.isCurrentUser(r.executor);
//                if (!isOwner) {
//                    htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.assignTask(" + r.id + ",\"" + Ticket.Util.getCurrentUserObj().id + "\")' >分配给我</a>  ");
//                } else {
//                    if (r.dataType == 1) {
//                        htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.doTaskCheck(" + r.id + ")' >检查</a>  ");
//                    }
//
//                }
//                htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.assignTask(" + r.id + ")' >分配</a>  ");
//                htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.openHistory(" + r.id + ")' >详细</a>  ");
                try {
                    var jsonObj = JSON.parse(r.detail)
                    if (jsonObj.hasOwnProperty("channelQipuId")) {
                        htmlArr.push("<a href='javascript:;' onclick='Ticket.Util.openStream(" + jsonObj.channelQipuId + ")' >直播流</a>  ");
                    }
                } catch (e) {
					console.log(e);
                }


                // htmls.push('<a href="./live_stream.html?qipuId='+ r.qipuId+'&id=' + r.id + '&name=' +  encodeURIComponent(name.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">")) + '&livetype=' + r.liveType + '&universalcode=' + r.universalCode.toLowerCase() + '" class="' + stream + '" target="_blank">直播流管理</a>');
                return htmlArr.join(" ");
            },
            reporter: function (v, o, r) {
                if (v == "_system_") {
                    return "";
                }
                return v;
            },
            executor: function (v, o, r) {
                if (v == null) {
                    return "";
                }
                var ret = "";
                var response = Ticket.Dao.getWorkers();
                if (response != null && response.data != null) {
                    $.each(response.data, function (idx, element) {
                        if (element.val == v) {
                            ret = element.desc;
                            return false;
                        }
                    })
                }
                return ret;
            },
            dataType: function (v, o, r) {
                switch (v) {
                    case 1:
                        return "直播工单";
                    default :
                        return "unknown " + v;
                }
            },
            oaDocEditorStatus: function (cellvalue, o, rowObject) {
                var ret = "";
                switch (cellvalue) {
                    case "unchecked":
                        ret = "待审核";
                        break;
                    case "checked":
                        ret = "总编室已确认";
                        break;
                    case "interrupt":
                        ret = "<span style='color: red'>中断</span>";
                        break;
                    default :
                        ret = "---"
                        break;
                }
                if (ret != "---") {
                    ret = "<a target='_blank' href='" + rowObject.oaDocUrl + "'>" + ret + "</a>"
                }
                return ret;
            },
            detail: function (v, o, r) {
                //   return "";
                return Ticket.Model.parseFormat(r.dataType, v);
            },
            deadline: function (v, o, r) {
                var ret = v;
                if (r.status == 0) {
                    var original = new Date(v.replace(/-/g, "/")).getTime();
                    var current = new Date().getTime();
                    var second = (original - current) / 1000 >> 0
                    if (second < 0) {
                        ret = "已过期";
                    } else {
                        ret = Ticket.Util.tranDurationFormat(second);
                        if (second < 600) {
                            ret = "<span style='color: red'>" + ret + "</span>"
                        }
                    }
                } else {
                    ret = "------";
                }
                return ret;
            },
            log_type: function (cellvalue, options, rowObject) {
                var ret = "";
                var enumNameData = Ticket.Dao.logType();
                $.each(enumNameData.data, function (index, element) {
                    if (cellvalue == element.key) {
                        ret = element.desc;
                        return false;
                    }
                })
                return ret;
            }
        },
        buildTicketDataParams: function (sqlArr, sqlValueArr, fillMode) {
            var length = sqlArr.length;
            var params = {};
            var tempValue = null;
            for (var i = 0; i < length; i++) {
                tempValue = sqlValueArr[i];
                if (sqlValueArr[i] === "currentUser()") {
                    tempValue = fillMode == "true" ? Ticket.Util.getCurrentUserObj() : Ticket.Util.getCurrentUser();
                }
                params[sqlArr[i]] = tempValue;
            }
            return params;
        },
        getCurrentUser: function () {
            return auth.baseInfo.authInfo.email
        },
        getCurrentUserObj: function () {
            return  {id: auth.baseInfo.authInfo.email, label: auth.baseInfo.authInfo.userName}
        },
        fillBasicForm: function (params) {
            if ("EQS_reporter" in  params) {
                $("input[name=EQS_reporter]").suggest("setValue", params["EQS_reporter"]);
            }
            if ("EQS_executor" in  params) {
                $("input[name=EQS_executor]").suggest("setValue", params["EQS_executor"]);
            }
            if ("EQI_status" in params) {
                $("select[name=EQI_status]").val(params["EQI_status"]);
            }
        },
        getTicketDataList: function (params) {
            console.log(JSON.stringify(params));
            if ("EQL_id" in params) {
                if (!EpgWeb.Plugin.Validate.checkNum(params["EQL_id"])) {
                    EpgWeb.Plugin.showTips({content: "参数错误", type: "error"});
                    return;
                }
            }

            $("#listGrid").jqGrid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: {paramsObj: JSON.stringify(params), orderObj: JSON.stringify({order: "asc", orderBy: "deadline"})}
            }).trigger('reloadGrid');
        },
        bindFoldDiv: function () {
            $("span[name=span_fold]").css({cursor: "pointer"});
            $("span[name=span_extend]").css({cursor: "pointer"});
            $("span[name=span_fold]").bind("click", function (event) {
                var $target = $(event.currentTarget);
                $target.parent().find("span[name=span_extend]").show();
                $target.hide();
                var name = $target.parent().attr("foldTarget");
                if (name == null || name.length < 1) {
                    name = "folder";
                }
                $target.parent().parent().find("div[name=" + name + "]").hide();
            });
            $("span[name=span_extend]").hide();
            $("span[name=span_extend]").bind("click", function (event) {
                var $target = $(event.currentTarget);
                $target.parent().find("span[name=span_fold]").show();
                $target.hide();
                var name = $target.parent().attr("foldTarget");
                if (name == null || name.length < 1) {
                    name = "folder";
                }
                $target.parent().parent().find("div[name=" + name + "]").show();
            });
        },
        checkSubmit: function () {
            var params = {};
            var elementArr = $.makeArray($("#dlg_checkList").find("input[type=radio]:checked"));
            if (Ticket.Config.CHECK_LIST_LEN > elementArr.length) {
                EpgWeb.Plugin.showTips({content: "尚有项目未检查", type: "error"});
                return
            }
            $.each(elementArr, function (i, element) {
                params[element.name] = element.value;
            })
            $("#dlg_checkList").dialog("close");
        },
        checkClosed: function () {
            $("#dlg_checkList").dialog("close");
        },
        openDlgCheckList: function () {
            var self = this;
            Ticket.Dao.getCheckList({dataId: Ticket.Dao.cfgName.entityId }, function (rdata) {
                if (rdata != null && rdata.code == Ticket.Config.CODE_SUC) {
                    self.fillDataCheckList(rdata.data);
                    $("#dlg_checkList").dialog("open");
                }
            });
        },
        fillDataCheckList: function (dataEntity) {
            //  $("#dlg_checkList").find("")
        },
        transToDevMode: function () {
            $("div[name=in_dev_div]").css({display: "inline-block"})
            $("#listGrid").setGridParam().showCol("operator_ticket_data").trigger("reloadGrid");
        },
        isCurrentUser: function (email) {
            return email == this.getCurrentUserObj().id;
        },
        decodeDeadline: function (selectValue) {
            var self = this;
            var startIndex = 0;
            var objArr = [];
            var nowTime = new Date();
            var nowValue = Ticket.Util.formatDateTimeFormat(nowTime)
            while (startIndex < selectValue.length) {
                var obj = {key: "", value: "", result: ""}
                var keySplit = selectValue.indexOf("=", startIndex);
                var valueEnd = selectValue.indexOf(";", keySplit + 1);
                obj.key = selectValue.slice(startIndex, keySplit);
                if (valueEnd == -1) {
                    valueEnd = selectValue.length;
                }
                obj.value = selectValue.slice(keySplit + 1, valueEnd);
                startIndex = valueEnd + 1;
                if (obj.value == "now()") {
                    obj.result = nowValue;
                } else if (obj.value.startsWith("func")) {
                    obj.result = self.decodeTimeFun(obj.value.slice(5, obj.value.length - 1).split(","), nowTime)
                }
                objArr.push(obj);
            }
            return objArr;
        },
        decodeTimeFun: function (paramsArr, baseTime) {
            var type = paramsArr[0];
            var time = paramsArr[1] == "now()" ? baseTime : new Date(paramsArr[1]);
            var changeValue = parseInt(paramsArr[2]);
            var ret = null;
            switch (type) {
                case "addhour":
                    time.setTime(time.getTime() + changeValue * 1000 * 3600);
                    ret = this.formatDateTimeFormat(time)
                    break;
            }
            return ret;
        },
        openHistory: function (entityId) {
            $("#ticketLogDiv").dialog("open");
            $('#logList').jqGrid('setGridParam', {
                page: 1,
                datatype: "json",
                postData: {id: entityId}
            }).trigger('reloadGrid');
        },
        openStream: function (channelQipuId) {
            Ticket.Dao.getChannelDataList({qipuId: channelQipuId}, function (data) {
                if (data != null && data.code == "A00000") {
                    if (data.data.result.length == 1) {
                        var r = data.data.result[0];
                        var openUrl = "live_stream.html?qipuId=" + r.qipuId + "&id=" + r.id + '&name=' + encodeURIComponent(r.name.replace(/&amp;/g, "&").replace(/&lt;/g, "<").replace(/&gt;/g, ">")) + '&livetype=' + r.liveType + '&universalcode=' + r.universalCode.toLowerCase();
                        window.open(openUrl);
                    }
                } else {
                    console.log("请求失败");
                }
            })
        },

        openAssignTaskDlg: function (entityId) {
            $("#workerDiv").dialog("open");
            $("input[name=assign_ticket_id]").val(entityId)
            $("select[name=assign_worker]").val("");
        },
        assignTask: function (entityId, email) {
            if (email == null) {
                this.openAssignTaskDlg(entityId);
            } else {
                Ticket.Dao.assignTask({id: entityId, executor: email}, function (data) {
                    if (data == null || data.code != Ticket.Config.CODE_SUC) {
                        EpgWeb.Plugin.showTips({type: "error", content: "请求失败：" + data.msg});
                    }
                    $("#listGrid").trigger("reloadGrid");
                })
            }
        },
        doTaskCheck: function (entityId) {
            var self = this;
            Ticket.Dao.getCheckList({dataId: entityId }, function (rdata) {
                if (rdata != null && rdata.code == Ticket.Config.CODE_SUC) {
                    self.fillDataCheckList(rdata.data);
                    $("#dlg_checkList").dialog("open");
                }
            });
        }

    });
});